package cn.xerllent.quartz.utils;

import cn.hutool.core.collection.CollectionUtil;
import cn.xerllent.common.exception.BadRequestException;
import cn.xerllent.quartz.entity.QuartzJob;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;


/**
 */
@Slf4j
@Component
public class QuartzManage {

    private static final String JOB_NAME = "TASK_";

    @Resource(name = "scheduler")
    private Scheduler scheduler;

    public void addJob(QuartzJob quartzJob) {
        try {
            /**
             * 构建job信息,quartzJob.getBean()一定要继承org.springframework.scheduling.quartz.QuartzJobBean方法，DataMap数据才会通过set注入bean实体内，继承org.quartz.Job参数无注入
             * */ 
            JobDetail jobDetail = JobBuilder.newJob((Class<? extends Job>) Class.forName(quartzJob.getBean())).
                    withIdentity(JOB_NAME + quartzJob.getId())
                    .withDescription(quartzJob.getName()).build();
            
//            if(CollectionUtil.isNotEmpty(quartzJob.getParams()) ) {
//            	jobDetail.getJobDataMap().putAll(quartzJob.getParams());
//                //cronTrigger.getJobDataMap().put(QuartzJob.JOB_KEY, quartzJob);
//            }

            //通过触发器名和cron 表达式创建 Trigger
            Trigger cronTrigger = TriggerBuilder.newTrigger()
                    .withIdentity(JOB_NAME + quartzJob.getId())
                    .startNow()
                    .withSchedule(CronScheduleBuilder.cronSchedule(quartzJob.getCron()))
                    .build();

            if(CollectionUtil.isNotEmpty(quartzJob.getParams()) ) {
                cronTrigger.getJobDataMap().putAll(quartzJob.getParams());
                //cronTrigger.getJobDataMap().put(QuartzJob.JOB_KEY, quartzJob);
            }

            //重置启动时间
            ((CronTriggerImpl) cronTrigger).setStartTime(new Date());

            //执行定时任务
            scheduler.scheduleJob(jobDetail, cronTrigger);

            // 暂停任务
            if (!quartzJob.getEnabled()) {
                pauseJob(quartzJob);
            }
        } catch (Exception e) {
            log.error("创建定时任务失败", e);
            throw new BadRequestException("创建定时任务失败"+e.getMessage());
        }
    }

    /**
     * 更新job cron表达式
     * @param quartzJob /
     */
    public void updateJobCron(QuartzJob quartzJob) {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(JOB_NAME + quartzJob.getId());
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            // 如果不存在则创建一个定时任务
            if (trigger == null) {
                addJob(quartzJob);
                trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            }
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(quartzJob.getCron());
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
            //重置启动时间
            ((CronTriggerImpl) trigger).setStartTime(new Date());
            if(CollectionUtil.isNotEmpty(quartzJob.getParams()) ) {
            	trigger.getJobDataMap().putAll(quartzJob.getParams());
            }

            scheduler.rescheduleJob(triggerKey, trigger);
            // 暂停任务
            if (!quartzJob.getEnabled()) {
                pauseJob(quartzJob);
            }
        } catch (Exception e) {
            log.error("更新定时任务失败", e);
            throw new BadRequestException("更新定时任务失败");
        }

    }

    /**
     * 删除一个job
     * @param quartzJob /
     */
    public void deleteJob(QuartzJob quartzJob) {
        try {
            JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getId());
            scheduler.pauseJob(jobKey);
            scheduler.deleteJob(jobKey);
        } catch (Exception e) {
            log.error("删除定时任务失败", e);
            throw new BadRequestException("删除定时任务失败");
        }
    }

    /**
     * 恢复一个job
     * @param quartzJob /
     */
    public void resumeJob(QuartzJob quartzJob) {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(JOB_NAME + quartzJob.getId());
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            // 如果不存在则创建一个定时任务
            if (trigger == null) {
                addJob(quartzJob);
            }
            JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getId());
            scheduler.resumeJob(jobKey);
        } catch (Exception e) {
            log.error("恢复定时任务失败", e);
            throw new BadRequestException("恢复定时任务失败");
        }
    }

    /**
     * 立即执行job
     * @param quartzJob /
     */
    public void runJobNow(QuartzJob quartzJob) {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(JOB_NAME + quartzJob.getId());
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            // 如果不存在则创建一个定时任务
            if (trigger == null) {
                addJob(quartzJob);
            }
            JobDataMap dataMap = null;
            if(CollectionUtil.isNotEmpty(quartzJob.getParams()) ) {
            	dataMap = new JobDataMap(quartzJob.getParams());
            }
            
            //dataMap.put(QuartzJob.JOB_KEY, quartzJob);
            JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getId());
            scheduler.triggerJob(jobKey, dataMap);
        } catch (Exception e) {
            log.error("定时任务执行失败", e);
            throw new BadRequestException("定时任务执行失败");
        }
    }

    /**
     * 暂停一个job
     * @param quartzJob /
     */
    public void pauseJob(QuartzJob quartzJob) {
        try {
            JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getId());
            scheduler.pauseJob(jobKey);
        } catch (Exception e) {
            log.error("定时任务暂停失败", e);
            throw new BadRequestException("定时任务暂停失败");
        }
    }
    
    /**
     * 测试一个QuartzJob是否正确配置，否则抛出错误信息,
     * 测试时会分配一个测试id，
     * */
    public void testJob(QuartzJob quartzJob) {
    	String testId = JOB_NAME + "test0000";
        try {
        	//1验证Job是否正确
            JobBuilder.newJob((Class<? extends Job>) Class.forName(quartzJob.getBean())).
                    withIdentity(testId)
                    .withDescription(quartzJob.getName()).build();
        } catch (Exception e) {
            throw new BadRequestException("定时任务bean类型有误:"+e.getMessage());
        }
        
        try {
        	//2验证cron是否正确
        	TriggerBuilder.newTrigger()
                    .withIdentity(testId)
                    .startNow()
                    .withSchedule(CronScheduleBuilder.cronSchedule(quartzJob.getCron()))
                    .build();
	    } catch (Exception e) {
	        throw new BadRequestException("定时任务cron表达式有误:"+e.getMessage());
	    }
    }
}
